import os
import sys
import hashlib
OUT_BIN = "flash_all.bin"
CHECKMD5_BIN = ["app.bin", "dsp.bin", "module.bin", "pcm.bin"]

if (len(sys.argv) < 2):
    print ("Usage: " + sys.argv[0] + " <bin_dir>")
else:
    bin_dir = sys.argv[1]
    bin_all = OUT_BIN
    allHandle = open(bin_all, "wb")
    bins = os.listdir(bin_dir)
    for bin in bins:
        if bin == OUT_BIN:
            continue
        bin_path = bin_dir + os.sep + bin
        if (os.path.isfile(bin_path) == False):
            print "WRN:skip non-file:", bin_path
            continue
        if (not bin_path.endswith(".bin")):
            print "WRN:skip non-bin:", bin_path
            continue
        lines = []
        if (bin in CHECKMD5_BIN):
            (filename, extension) = os.path.splitext(bin)
            lines.append(filename + '_md5.bin' + "\n")
        else:
            lines.append(bin + "\n")
        size = os.path.getsize(bin_path)
        if (bin in CHECKMD5_BIN):
            size = size + 256
        lines.append(str(size) + "\n")
        fp = open(bin_path, "rb")
        content = fp.read()
        fp.close()
        if (bin in CHECKMD5_BIN):
            file_md5 = hashlib.md5(content).hexdigest()
            lines.append(file_md5 + bytearray(256 - 32) + content)
        else:
            lines.append(content)
        allHandle.writelines(lines)
    allHandle.close()
